package Leo.ribbon;

import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.PingUrl;
import com.netflix.niws.client.http.RestClient;
import com.netflix.config.ConfigurationManager;

public class RibbonStarter {

    public static void main(String[] args) throws Exception {
        ConfigurationManager.loadPropertiesFromResources("/ribbon.properties");
        // 设置请求的服务器
        ConfigurationManager.getConfigInstance().setProperty(
                "my-client.ribbon.listOfServers",
                "localhost:8080,localhost:8081");

// 配置Ping 处理类
        ConfigurationManager.getConfigInstance().setProperty(
                "my-client.ribbon.NFLoadBalancerPingClassName",
                PingUrl.class.getName());
// 配置Ping 时间间隔
        ConfigurationManager.getConfigInstance().setProperty(
                "my-client.ribbon.NFLoadBalancerPingInterval",
                2);
        //设置负载均衡规则
        ConfigurationManager.getConfigInstance().setProperty("my-client.ribbon.NFLoadBalancerRuleClassName",LoadBalanceRuleImpl.class.getName());
        //可以通过读取properties的方法进行配置，或者像上文那样，通过代码配置
//        ConfigurationManager.loadPropertiesFromResources("ribbon.properties");

        // 获取REST
// 获取REST 请求客户端
        RestClient client = (RestClient) ClientFactory.getNamedClient("my-client");
        ILoadBalancer loadBalancer = client.getLoadBalancer();
        System.out.println(loadBalancer instanceof BaseLoadBalancer);
// 创建请求实例
        HttpRequest request = HttpRequest.newBuilder().uri("/person/1").build();
// 发送6 次请求到服务器中
        for (int i = 0; i < 6; i++) {
            HttpResponse response = null;

            response = client.executeWithLoadBalancer(request);

            String result = response.getEntity(String.class);//此行代码需要引入com.google.guava这个maven
            System.out.println(result);
        }
    }
}
